package sample.stormax.pres.news.utils.http;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;

public class HttpUtils {
    private static final String TAG = HttpUtils.class.getSimpleName();
    private static HttpURLConnection connection = null;

    private static final String GET_METHOD = "GET";
    private static final String POST_METHOD = "POST";

    public static final String ERROR_TIMEOUT = "TIMEOUT";

    public static final String charsetName = "UTF-8";

    private static final int connectTimeOut = 8000;
    private static final int readTimeOut = 8000;

    static {
//        System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
//        System.setProperty("sun.net.client.defaultReadTimeout", "2000");
    }

    /**
     * 建立链接，设置超时时间为8秒
     *
     * @param path 链接地址
     * @return 已经建立完成的链接
     */
    private static HttpURLConnection getConnection(String path) {
        Log.d(TAG, "getConnection.......");
        URL url;
        try {
            url = new URL(path);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(GET_METHOD);
            connection.setConnectTimeout(connectTimeOut);
            connection.setReadTimeout(readTimeOut);
            connection.connect();
            if (connection.getResponseCode() == 200) {
                Log.d(TAG, "connected");
                return connection;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 向服务器发送请求，默认编码为UTF-8
     *
     * @param path 请求地址
     * @return 从服务器获取的json数据包，或者<code>TIMEOUT</code>超时
     */
    public static String sendRequest(String path) {
        StringBuilder response = new StringBuilder();
        BufferedReader reader = null;
        InputStream in = null;
        try {
            connection = getConnection(path);
            Log.d(TAG, "waiting response");
            in = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in, charsetName));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            Log.d(TAG, "got response" + response);
        } catch (MalformedURLException e) {
            Log.e(TAG, "Malformed URL!");
            return ERROR_TIMEOUT;
        } catch (SocketTimeoutException e) {
            Log.e(TAG, "Socket Time Out!");
            return ERROR_TIMEOUT;
        } catch (IOException e) {
            Log.e(TAG, "IO Exception");
            e.printStackTrace();
            return ERROR_TIMEOUT;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }

            try {
                if (in != null)
                    in.close();
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response.toString();
    }

}